<template>
  <div class="query-container">
    <!-- 上方表单区域 -->
    <div class="form-section">
      <h3 class="form-title">请输入查询信息</h3>
      <el-form :model="queryForm" :rules="rules" ref="queryFormRef" label-width="100px">
        <div class="form-content">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="queryForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
              @change="handleStartTimeChange"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="queryForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
          <el-form-item label="流域ID" prop="basinId">
            <el-select
              v-model="queryForm.basinId"
              filterable
              placeholder="请选择流域"
              style="width: 100%"
            >
              <el-option
                v-for="item in basinOptions"
                :key="item.value"
                :label="`${item.label} (${item.value})`"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        
        <!-- 在按钮组添加新按钮 -->
        <div class="form-buttons">
          <el-button 
            type="warning" 
            :icon="Search" 
            :loading="loading" 
            @click="queryHistoricalData">
            历史雨水情查询
          </el-button>
          <el-button 
            type="primary" 
            :icon="Search" 
            :loading="loading" 
            :disabled="!historicalQueryResult" 
            @click="getForecastData">
            流量趋势
          </el-button>
          <el-button 
            type="success" 
            :icon="Document" 
            :loading="loading" 
            :disabled="!historicalQueryResult" 
            @click="compareHistoryData">
            历史洪水记录对比
          </el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 下方内容区域 -->
    <div class="content-section">
      <!-- 添加 tab 组件 -->
      <el-tabs v-model="activeView" class="query-tabs">
        <el-tab-pane label="历史雨水情查询" name="historical">
          <!-- 历史数据图表 -->
          <div v-show="historicalChartData" class="historical-chart-container">
            <div class="historicalChart" style="width: 100%; height: 600px;"></div>
          </div>
          <!-- 空状态 -->
          <div v-show="!historicalChartData" class="empty-chart">
            <el-empty description="请在上方输入查询条件并点击历史数据查询按钮" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="流量趋势_" name="forecast_">
        </el-tab-pane>
        
        <el-tab-pane label="流量趋势" name="forecast">
          <!-- 预测图表 -->
          <div v-show="forecastChartData" class="forecast-chart-container">
            <div class="forecastChart" style="width: 100%; height: 600px;"></div>
          </div>
          <!-- 空状态 -->
          <div v-show="!forecastChartData" class="empty-chart">
            <el-empty description="请在上方输入查询条件并点击流量趋势按钮" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="历史洪水记录" name="history">
          <!-- 历史数据表格 -->
          <div v-show="historyData.length > 0" class="history-table-container">
            <el-table
              v-loading="loading"
              :data="historyData"
              style="width: 100%"
              border
            >
              <el-table-column
                prop="id"
                label="相似度"
                width="180"
              />
              <el-table-column
                prop="name"
                label="洪水名字"
                width="180"
              />
              <el-table-column
                prop="detailUrl"
                label="详细数据"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  <el-link
                    type="primary"
                     @click.prevent="handleDetailClick(row.detailUrl)"
                      >
                    查看详情
                  </el-link>

                </template>
              </el-table-column>
            </el-table>
          </div>
          <!-- 空状态 -->
          <div v-show="historyData.length === 0" class="empty-chart">
            <el-empty description="请在上方输入查询条件并点击查询历史数据按钮" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="历史详情" name="historyDetailChart">
          <div style="width: 100%; height: 100%; position: relative;">
            <!-- 关闭按钮 -->
            <el-button
              :icon="Close"
              circle
              type="danger"
              size="small"
              class="chart-close-button"
              @click="activeView = 'history'"
            />
            <!-- 当前流量图表 -->
            <div class="history-chart-container">
              <div id="currentChart" style="width: 100%; height: 300px;"></div>
            </div>
            <!-- 相似流量图表 -->
            <div class="history-chart-container">
              <div id="similarChart" style="width: 100%; height: 300px;"></div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { Close } from '@element-plus/icons-vue'
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import { Search, Document } from '@element-plus/icons-vue'

// ... 在 script setup 部分添加数据源
const basinOptions = [
  { value: 'CHN_songliao_21400550', label: '土门子水库' },
  { value: 'CHN_songliao_21400800', label: '转角楼水库' },
  { value: 'CHN_songliao_21401050', label: '英那河水库' },
  { value: 'CHN_songliao_21401300', label: '朱家隈水库' },
  { value: 'CHN_songliao_21401550', label: '碧流河水库' },
  { value: 'CHN_songliao_21401900', label: '刘大水库' }
]
//
const selectedHistoryChartData = ref(null)
const historyDetailChartInstance = ref(null)

//
// 当前激活的视图（forecast: 趋势图, history: 历史数据）
const activeView = ref('forecast')

// 表单校验规则
const rules = {
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  basinId: [{ required: true, message: '请输入流域ID', trigger: 'blur' }]
}

// 查询相关状态
const queryForm = ref({
  startTime: '',
  endTime: '',
  basinId: '',
})
const queryFormRef = ref(null)
const forecastChartData = ref(null)
const forecastChartInstance = ref(null)
const router = useRouter()

// 初始化预测图表
const initForecastChart = () => {
  if (!forecastChartData.value) return;

  const chartDom = document.querySelector('.forecastChart');
  if (!chartDom) return;

  // 处理当前时间数据、预测数据和标签数据
  const currentTimeData = forecastChartData.value.current_time_data.map(item => [item.time * 1000, item.flow]);
  const predictionsData = forecastChartData.value.predictions.map(item => [item.time * 1000, item.flow]);
  const labelData = forecastChartData.value.label_data.map(item => [item.time * 1000, item.flow]);
  const rainfallData = forecastChartData.value.current_time_data.map(item => [item.time * 1000, item.rainfall]);
  const predictedRainfallData = forecastChartData.value.predictions.map(item => [item.time * 1000, item.rainfall]);

  // 确保数据连续性
  if (currentTimeData.length > 0 && predictionsData.length > 0) {
    const lastCurrentTime = currentTimeData[currentTimeData.length - 1][0];
    const firstPredictionTime = predictionsData[0][0];
    if (lastCurrentTime !== firstPredictionTime) {
      const lastCurrentFlow = currentTimeData[currentTimeData.length - 1][1];
      predictionsData.unshift([lastCurrentTime, lastCurrentFlow]);
    }
  }

  if (currentTimeData.length > 0 && labelData.length > 0) {
    const lastCurrentTime = currentTimeData[currentTimeData.length - 1][0];
    const firstLabelTime = labelData[0][0];
    if (lastCurrentTime !== firstLabelTime) {
      const lastCurrentFlow = currentTimeData[currentTimeData.length - 1][1];
      labelData.unshift([lastCurrentTime, lastCurrentFlow]);
    }
  }

  forecastChartInstance.value = echarts.init(chartDom);
  const option = {
    title: {
      text: `流量预测趋势 - ${queryForm.value.basinId}`,
      subtext: `${new Date(forecastChartData.value.current_time_data[0].time * 1000).toLocaleString('zh-CN')} 至 ${new Date(forecastChartData.value.label_data[forecastChartData.value.label_data.length - 1].time * 1000).toLocaleString('zh-CN')}`,
      left: 'center',
      top: 0,
      padding: [0, 0, 30, 0]
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        const time = new Date(params[0].value[0]).toLocaleString('zh-CN');
        let result = `${time}<br/>`;
        params.forEach(param => {
          let value = param.value[1];
          let unit = '';
          if (param.seriesName.includes('水位')) {
            unit = ' m';
          } else if (param.seriesName === '降雨量') {
            unit = ' mm';
          } else {
            unit = ' m³/s';
          }
          result += `${param.seriesName}: ${value}${unit}<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['当前流量', '预测流量', '实际流量', '当前降雨量', '预测降雨量', '实际降雨量'],
      bottom: 10,
      left: 'center'
    },
    grid: {
      right: '10%',
      left: '10%',
      bottom: '15%'
    },
    xAxis: [
      {
        type: 'time',
        position: 'bottom',
        axisLabel: {
          formatter: (value) => new Date(value).toLocaleString('zh-CN', { 
            month: 'numeric', 
            day: 'numeric', 
            hour: 'numeric', 
            minute: 'numeric'  
          })
        }
      },
      {
        type: 'time',
        show: false, // 隐藏重复的刻度
        position: 'top',
        axisLabel: {
          formatter: (value) => new Date(value).toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            hour: 'numeric',
            minute: 'numeric'
          })
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '流量 (m³/s)',
        position: 'left',
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '降雨量 (mm)',
        inverse: true,
        position: 'right',
        axisLine: {
          show: true
        },
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '当前流量',
        type: 'line',
        yAxisIndex: 0,
        data: currentTimeData,
        itemStyle: {
          color: '#0076f6'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '预测流量',
        type: 'line',
        yAxisIndex: 0,
        data: predictionsData,
        itemStyle: {
          color: '#41b783'
        },
        lineStyle: {
          width: 2, type: 'dashed'
        }
      },
      {
        name: '实际流量',
        type: 'line',
        yAxisIndex: 0,
        data: labelData,
        itemStyle: {
          color: '#3d97f8'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '当前降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: rainfallData,
        barWidth: '60%',
        itemStyle: {
          color: '#fb8c00'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '预测降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: predictedRainfallData,
        barWidth: '60%',
        itemStyle: {
          color: '#7bb69d'
        },
        lineStyle: {
          width: 2,
        }
      },
      {
        name: '实际降雨量', 
        type: 'bar',
        yAxisIndex: 1, 
        data: forecastChartData.value.label_data.map(item => [item.time * 1000, item.rainfall]),
        barWidth: '60%',
        itemStyle: { color: '#ffb74d'},
        lineStyle: { width: 2, }      
      }    
    ]  
  };

  forecastChartInstance.value.setOption(option);

  // 窗口大小变化时自适应
  window.addEventListener('resize', () => {
    forecastChartInstance.value?.resize();
  });
};

//添加代码
const handleDetailClick = async (url) => {
  try {
    const res = await fetch(url)
    const json = await res.json()

    // 提取当前数据
    const currentFlow = json.current_data?.current_time_data?.map(i => [i.time * 1000, i.flow]) || []
    const currentRainfall = json.current_data?.current_time_data?.map(i => [i.time * 1000, i.rainfall]) || []
    const currentAfter10 = json.current_data?.after10_label_data?.map(i => [i.time * 1000, i.flow]) || []
    const currentAfter10Rainfall = json.current_data?.after10_label_data?.map(i => [i.time * 1000, i.rainfall]) || []

    // 提取相似历史数据
    const similarFlow = json.similar_history_segments?.data?.map(i => [i.time * 1000, i.flow]) || []
    const similarRainfall = json.similar_history_segments?.data?.map(i => [i.time * 1000, i.rainfall]) || []
    const similarAfter10 = json.similar_history_segments?.after10_data?.map(i => [i.time * 1000, i.flow]) || []
    const similarAfter10Rainfall = json.similar_history_segments?.after10_data?.map(i => [i.time * 1000, i.rainfall]) || []

    selectedHistoryChartData.value = {
      currentFlow,
      currentRainfall,
      currentAfter10,
      currentAfter10Rainfall,
      similarFlow,
      similarRainfall,
      similarAfter10,
      similarAfter10Rainfall
    }

    activeView.value = 'historyDetailChart'

    nextTick(() => {
      drawSelectedHistoryChart()
    })
  } catch (err) {
    ElMessage.error(`加载数据失败: ${err.message}`)
  }
}

//图表
const drawSelectedHistoryChart = () => {
  const currentChartDom = document.getElementById('currentChart')
  const similarChartDom = document.getElementById('similarChart')

  if (!currentChartDom || !similarChartDom || !selectedHistoryChartData.value) return

  const {
    currentFlow,
    currentRainfall,
    currentAfter10,
    currentAfter10Rainfall,
    similarFlow,
    similarRainfall,
    similarAfter10,
    similarAfter10Rainfall
  } = selectedHistoryChartData.value

  // 清除旧图表实例
  echarts.dispose(currentChartDom)
  echarts.dispose(similarChartDom)

  const currentChart = echarts.init(currentChartDom)
  const similarChart = echarts.init(similarChartDom)

  const xAxisOption = {
    type: 'time',
    axisLabel: {
      formatter: (value) =>
        new Date(value).toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric'
        })
    }
  }

  // 当前洪水图表配置
  const currentOption = {
    title: { text: '当前流量趋势', left: 'center' },
    tooltip: { 
      trigger: 'axis',
      formatter: function(params) {
        const time = new Date(params[0].value[0]).toLocaleString('zh-CN')
        let result = `${time}<br/>`
        params.forEach(param => {
          const value = param.value[1]
          const unit = param.seriesName.includes('降雨量') ? ' mm' : ' m³/s'
          result += `${param.seriesName}: ${value}${unit}<br/>`
        })
        return result
      }
    },
    legend: { 
      data: ['当前流量', '当前流量(10天后)', '当前降雨量', '当前降雨量(10天后)'], 
      bottom: 0 
    },
    xAxis: [
      // 折线图的横轴（底部正常显示）
      {
        type: 'time',
        position: 'bottom',
        axisLabel: {
          formatter: (value) =>
            new Date(value).toLocaleString('zh-CN', {
              month: 'numeric',
              day: 'numeric',
              hour: 'numeric',
              minute: 'numeric'
            })
        }
      },
      // 柱状图的横轴（顶部显示，用于对齐）
      {
        type: 'time',
        show: false, // 隐藏重复的刻度
        position: 'top',  
        axisLabel: {
          formatter: (value) =>
            new Date(value).toLocaleString('zh-CN', {
              month: 'numeric',
              day: 'numeric',
              hour: 'numeric',
              minute: 'numeric'
            })
        }
      },
    ],
    yAxis: [
      { 
        type: 'value', 
        name: '流量 (m³/s)',
        position: 'left',
        axisLine: { show: true }
      },
      {
        type: 'value',
        name: '降雨量 (mm)',
        inverse: true,
        position: 'right',
        axisLine: { show: true }
      }
    ],
    grid: { left: '10%', right: '10%', bottom: '15%' },
    series: [
      { 
        name: '当前流量', 
        type: 'line', 
        yAxisIndex: 0,
        data: currentFlow, 
        lineStyle: { width: 2 }
      },
      { 
        name: '当前流量(10天后)', 
        type: 'line', 
        yAxisIndex: 0,
        data: currentAfter10, 
        lineStyle: { type: 'dashed', width: 2 } 
      },
      {
        name: '当前降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: currentRainfall,
        barWidth: '60%',
        itemStyle: { color: '#fb8c00' },
      },
      {
        name: '当前降雨量(10天后)',
        type: 'bar',
        yAxisIndex: 1,
        data: currentAfter10Rainfall,
        barWidth: '60%',
        itemStyle: { color: '#ffb74d' },
      }
    ]
  }

  // 相似洪水图表配置
  const similarOption = {
    title: { text: '相似历史流量趋势', left: 'center' },
    tooltip: { 
      trigger: 'axis',
      formatter: function(params) {
        const time = new Date(params[0].value[0]).toLocaleString('zh-CN')
        let result = `${time}<br/>`
        params.forEach(param => {
          const value = param.value[1]
          const unit = param.seriesName.includes('降雨量') ? ' mm' : ' m³/s'
          result += `${param.seriesName}: ${value}${unit}<br/>`
        })
        return result
      }
    },
    legend: { 
      data: ['相似流量', '相似流量(10天后)', '相似降雨量', '相似降雨量(10天后)'], 
      bottom: 0 
    },
    xAxis:[
      // 折线图的横轴（底部正常显示）
      {
        type: 'time',
        position: 'bottom',
        axisLabel: {
          formatter: (value) =>
            new Date(value).toLocaleString('zh-CN', {
              month: 'numeric',
              day: 'numeric',
              hour: 'numeric',
              minute: 'numeric'
            })
        }
      },
      // 柱状图的横轴（顶部显示，用于对齐）
      {
        type: 'time',
        show: false, // 隐藏重复的刻度
        position: 'top',  
        axisLabel: {
          formatter: (value) =>
            new Date(value).toLocaleString('zh-CN', {
              month: 'numeric',
              day: 'numeric',
              hour: 'numeric',
              minute: 'numeric'
            })
        }
      },
    ],
    yAxis: [
      { 
        type: 'value', 
        name: '流量 (m³/s)',
        position: 'left',
        axisLine: { show: true }
      },
      {
        type: 'value',
        name: '降雨量 (mm)',
        inverse: true,
        position: 'right',
        axisLine: { show: true }
      }
    ],
    grid: { left: '10%', right: '10%', bottom: '15%' },
    series: [
      { 
        name: '相似流量', 
        type: 'line', 
        yAxisIndex: 0,
        data: similarFlow, 
        lineStyle: { width: 2 }
      },
      { 
        name: '相似流量(10天后)', 
        type: 'line', 
        yAxisIndex: 0,
        data: similarAfter10, 
        lineStyle: { type: 'dashed', width: 2 } 
      },
      {
        name: '相似降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: similarRainfall,
        barWidth: '60%',
        itemStyle: { color: '#fb8c00' },
      },
      {
        name: '相似降雨量(10天后)',
        type: 'bar',
        yAxisIndex: 1,
        data: similarAfter10Rainfall,
        barWidth: '60%',
        itemStyle: { color: '#ffb74d' },
      }
    ]
  }

  currentChart.setOption(currentOption)
  similarChart.setOption(similarOption)

  window.addEventListener('resize', () => {
    currentChart.resize()
    similarChart.resize()
  })
}
//收尾

// 添加格式化历史数据的工具函数
const formatHistoricalData = (data) => {
  if (!data || !data.data || !data.data.length) return ''
  
  let result = '关键时段数据：\n时间点        降雨量(mm)   流量(m³/s)\n----------------------------------------\n'
  
  data.data.forEach(item => {
    const date = new Date(item.time * 1000)
    const day = date.getDate()
    const hour = date.getHours().toString().padStart(2, '0')
    result += `${day}日${hour}:00时，降雨量${item.rainfall.toFixed(2)}mm，流量${item.flow.toFixed(1)}m³/s\n`
  })
  
  return result
}

// 获取预测数据
const getForecastData = async () => {
  try {
    // 表单验证
    await queryFormRef.value.validate()
    activeView.value = 'forecast'

    // 转换时间格式为Unix时间戳(秒)
    const startTime = Math.floor(new Date(queryForm.value.startTime).getTime() / 1000)
    const endTime = Math.floor(new Date(queryForm.value.endTime).getTime() / 1000)
    
    if (isNaN(startTime) || isNaN(endTime) || startTime >= endTime) {
      ElMessage.warning('请选择有效的时间范围')
      return
    }

    // 1. 先获取历史降雨数据
    const historyResponse = await fetch(
        'http://10.10.10.125:8002/api/history_rainfall',
        {
          method: 'POST',
          headers: {
            'accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            query: formatHistoricalData(historicalQueryResult.value)
          })
        }
      )
    
    const historyData = await historyResponse.json()
    
    // 2. 调用预测接口
    const response = await fetch(`http://10.10.10.125:8002/api/forecast?start_datetime=${startTime}&end_datetime=${endTime}&area_id=${queryForm.value.basinId}&top_n=3`,
      {
        method: 'POST',
        headers: {
          'accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(historyData.data) // 直接传递历史数据数组
      }
    )
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const forecastData = await response.json()
    forecastChartData.value = forecastData
    
    // 初始化预测图表
    nextTick(() => {
      initForecastChart()
    })
    
  } catch (error) {
    console.error('获取预测数据失败:', error)
    ElMessage.error(`获取预测数据失败: ${error.message}`)
  }
};

// 获取历史数据
const historyData = ref([])
const loading = ref(false)

const compareHistoryData = async () => {
  try {
    await queryFormRef.value.validate()
    loading.value = true
    activeView.value = 'history'

    const startTime = Math.floor(new Date(queryForm.value.startTime).getTime() / 1000)
    const endTime = Math.floor(new Date(queryForm.value.endTime).getTime() / 1000)
    const { basinId } = queryForm.value

    if (isNaN(startTime) || isNaN(endTime) || startTime >= endTime) {
      ElMessage.warning('请选择有效的时间范围')
      return
    }

    // 修改 compareHistoryData 函数中的请求部分
    const response = await fetch('http://10.10.10.125:8002/api/history_data', {
      method: 'POST',
      headers: {
        'accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        start_time: startTime,
        end_time: endTime,
        basin_id: basinId,
        request: formatHistoricalData(historicalQueryResult.value)  // 添加格式化后的历史数据
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    
    if (data.status === 'success' && data.resources) {
      historyData.value = data.resources.map(item => ({
        ...item,
        detailUrl: `http://10.10.10.125:8002/api/${item.history_segment}`
      }))
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    console.error('获取历史数据失败:', error)
    ElMessage.error(`获取历史数据失败: ${error.message}`)
    historyData.value = []
  } finally {
    loading.value = false
  }
}

const handleStartTimeChange = (time) => {
  if (time) {
    // 将开始时间转换为 Date 对象
    const startDate = new Date(time)
    // 计算三天后的时间
    const endDate = new Date(startDate.getTime() + (3 * 24 * 60 * 60 * 1000))
    // 格式化为指定格式
    queryForm.value.endTime = endDate.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-')
  }
}

// 添加历史数据查询相关状态
const historicalChartData = ref(null)
const historicalChartInstance = ref(null)

// 历史数据查询函数
// 在 script setup 中添加新的响应式变量
const historicalQueryResult = ref(null)  // 用于存储历史数据查询的结果

// 修改 queryHistoricalData 函数
const queryHistoricalData = async () => {
  try {
    await queryFormRef.value.validate()
    loading.value = true
    activeView.value = 'historical'

    const startTime = Math.floor(new Date(queryForm.value.startTime).getTime() / 1000)
    const endTime = Math.floor(new Date(queryForm.value.endTime).getTime() / 1000)
    
    if (isNaN(startTime) || isNaN(endTime) || startTime >= endTime) {
      ElMessage.warning('请选择有效的时间范围')
      return
    }

    const response = await fetch(
      `http://10.10.10.125:8002/api/get_test_rainfall/${startTime}/${endTime}/${queryForm.value.basinId}`,
      {
        headers: {
          'accept': 'application/json'
        }
      }
    )

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    if (data.status === 'success') {
      historicalChartData.value = data.data
      historicalQueryResult.value = data  // 保存查询结果
      nextTick(() => {
        initHistoricalChart()
      })
    } else {
      throw new Error('获取数据失败')
    }
  } catch (error) {
    console.error('获取历史数据失败:', error)
    ElMessage.error(`获取历史数据失败: ${error.message}`)
    historicalChartData.value = null
    historicalQueryResult.value = null  // 清空查询结果
  } finally {
    loading.value = false
  }
}

// 初始化历史数据图表
const initHistoricalChart = () => {
  if (!historicalChartData.value) return

  const chartDom = document.querySelector('.historicalChart')
  if (!chartDom) return

  // 处理数据
  const timeData = historicalChartData.value.map(item => item.time * 1000)
  const flowData = historicalChartData.value.map(item => [item.time * 1000, item.flow])
  const rainfallData = historicalChartData.value.map(item => [item.time * 1000, item.rainfall])

  historicalChartInstance.value = echarts.init(chartDom)
  const option = {
    title: {
      text: `历史数据 - ${queryForm.value.basinId}`,
      subtext: `${new Date(timeData[0]).toLocaleString('zh-CN')} 至 ${new Date(timeData[timeData.length - 1]).toLocaleString('zh-CN')}`,
      left: 'center',
      top: 0,
      padding: [0, 0, 30, 0]
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const time = new Date(params[0].value[0]).toLocaleString('zh-CN')
        return `${time}<br/>
                流量: ${params[0].value[1]} m³/s<br/>
                降雨量: ${params[1].value[1]} mm`
      }
    },
    legend: {
      data: ['流量', '降雨量'],
      bottom: 10,
      left: 'center'
    },
    grid: {
      right: '10%',
      left: '10%',
      bottom: '15%'
    },
    xAxis: [{
      type: 'time',
      position: 'bottom',
      axisLabel: {
        formatter: (value) => new Date(value).toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric'
        })
      }
    },
    {
      type: 'time',
      position: 'top',
      axisLabel: {
        formatter: (value) => new Date(value).toLocaleString('zh-CN', {
          month: 'numeric',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric'
        })
      }
    },],
    yAxis: [
      {
        type: 'value',
        name: '流量 (m³/s)',
        position: 'left',
        axisLine: { show: true },
        axisLabel: { formatter: '{value}' }
      },
      {
        type: 'value',
        name: '降雨量 (mm)',
        inverse: true,
        position: 'right',
        axisLine: { show: true },
        axisLabel: { formatter: '{value}' }
      }
    ],
    series: [
      {
        name: '流量',
        type: 'line',
        yAxisIndex: 0,
        data: flowData,
        itemStyle: { color: '#0076f6' },
        lineStyle: { width: 2 }
      },
      {
        name: '降雨量',
        type: 'bar',
        yAxisIndex: 1,
        data: rainfallData,
        barWidth: '60%',
        itemStyle: { color: '#fb8c00' }
      }
    ]
  }

  historicalChartInstance.value.setOption(option)

  // 窗口大小变化时自适应
  window.addEventListener('resize', () => {
    historicalChartInstance.value?.resize()
  })
}
</script>

<style scoped>
.query-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.form-section {
  padding: 20px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.form-content {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.form-content .el-form-item {
  margin-bottom: 0;
  flex: 1;
  min-width: 300px;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.form-title {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.content-section {
  flex: 1;
  padding: 20px;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.query-tabs {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.query-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: auto;
  height: auto;
}

.query-tabs :deep(.el-tab-pane) {
  height: 100%;
  overflow: auto;
}

.query-tabs :deep(.el-tabs__header .el-tabs__item:nth-child(3)) {
  display: none;
}
</style>
